﻿using Kinlo.Entitys; 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using XingLucifer.IBase.Enums;

namespace Kinlo.MESDocking
{
    /// <summary>
    /// 产品结果数据收集接口（单条）
    /// </summary>
    public class ProduceOpenAddInterface : MESInteractionBase
    {
        public ProduceOpenAddInterface(Action<string, string, string, string, string, long, DateTime, string, string, string, string> log, Action<string, string, string> dialog)
            : base(log, dialog, "产品结果数据收集接口单条")
        {
        }

        public override ResultTypes Interaction(string url, int timeout, int reconnect_count, DateTime dateTime, ProductionData[] production, Dictionary<string, object> parameters)
        {
            _stopwatch.Restart();
            string json = JsonSerializer.Serialize(parameters["parameter"], HttpHelper.Options);
            var result = Post(json, url, timeout, reconnect_count);
            _stopwatch.Stop();
            _log?.Invoke(production[0].BarCode, _name, result.Item2, json, result.Item1 ? "请求成功" : "请求异常",
                _stopwatch.ElapsedMilliseconds, dateTime, parameters["machineNo"]?.ToString() ?? "", parameters["producttype"].ToString() ?? "", this.GetType().Name,url);
            if (result.Item1)
            {
                var result_json = JsonSerializer.Deserialize<Dictionary<string,object>>(result.Item2);
                if (result_json["code"].ToString() != "200")
                {
                    _dialog?.Invoke(_name, result_json["code"].ToString(), result_json["errorMsg"].ToString());
                }
                else
                    return ResultTypes.合格;
            }
            else
            {
                _dialog?.Invoke(_name, "ERROR", result.Item2);
                return ResultTypes.MES上传失败;
            }
            return ResultTypes.MES_NG;
        }
    }
}
